package com.itheima.controller;

import com.itheima.common.CustomException;
import com.itheima.common.R;
import com.itheima.dto.CardDeletedIdDto;
import com.itheima.pojo.ShoppingCart;
import com.itheima.service.ShoppingCardService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("shoppingCart")
public class ShoppingCartController {

    @Resource
    private ShoppingCardService shoppingCardService;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 购物车列表
     * @return
     */
    @GetMapping("list")
    public R<List<ShoppingCart>> list() {
        return R.success(shoppingCardService.getList());

    }

    /**
     * 删除购物车商品
     * @param dto
     * @return
     */
    @PostMapping("sub")
    public R<String> deletedById(@RequestBody CardDeletedIdDto dto){

        if(Objects.isNull(dto)){
            throw new CustomException("删除失败，请重新删除");
        }
        Boolean res = shoppingCardService.removeByDishIdOrSetMealId(dto.getDishId(), dto.getSetmealId());

        return res?R.success("删除成功"):R.error("删除失败");
    }

    /**
     * 添加到购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("add")
    public R<String> addToCart(@RequestBody ShoppingCart shoppingCart){


        Boolean res = shoppingCardService.addToCart(shoppingCart);

        return res?R.success("添加成功"):R.error("添加失败");

    }


    @DeleteMapping("clean")
    public R<String> clean(){

        Boolean res = shoppingCardService.removeAll();

        return res?R.success("清空成功"):R.error("清空失败");
    }
}
